package com.terrace.web.tagext.tools;

import java.text.MessageFormat;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.terrace.web.constant.GlobalsConstant;
import com.terrace.db.system.mapper.entity.Lang;
import com.terrace.db.system.service.LangService;

/**
 * 常用语标签
 * @author jiangyg
 *
 */
public class LangTag extends TagSupport {
	
	private static final long serialVersionUID = -9065982986348087897L;

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(LangTag.class);
	
	/**
	 * 常用语键值
	 */
	private String key;
	
	/**
	 * 常用语参数
	 */
	private String arg;
	
	private LangService langService;

	@Override
	public int doStartTag() throws JspException {
		if (langService == null) {
			synchronized (LangTag.class) {
				if (langService == null) {
					WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.pageContext.getServletContext());
					langService = wac.getBean(LangService.class);
				}
			}
		}
		return EVAL_PAGE;
	}

	@Override
	public int doEndTag() throws JspException {
		try {
			if (StringUtils.isBlank(key)) {
				return EVAL_PAGE;
			}
			HttpSession session = this.pageContext.getSession();
			String langType = ObjectUtils.toString(session.getAttribute(GlobalsConstant.SYSTEM_LANG_TYPE));
			if (StringUtils.isBlank(langType)) {
				langType = "1";						// 默认汉语
				session.setAttribute(GlobalsConstant.SYSTEM_LANG_TYPE, langType);
				logger.warn("未获取到常用语类型，已设置默认中文。");
			}
			Lang lang = langService.selectLangContentByKey(key, langType);
			if (lang != null && StringUtils.isNotBlank(lang.getLangContent())) {
				JspWriter out = this.pageContext.getOut();
				if (StringUtils.isBlank(arg)) {
					out.print(lang.getLangContent());
				}
				if (StringUtils.isNotBlank(arg)) {
					out.print(MessageFormat.format(lang.getLangContent(), arg));
				}
			}
		} catch (Exception e) {
			logger.error("常用语获取出错：", e);
		}
		return EVAL_PAGE;
	}
	
	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public String getArg() {
		return arg;
	}

	public void setArg(String arg) {
		this.arg = arg;
	}

}
